package javax.core.common.encrypt;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 抽象信息加密基类
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/8/31 21:11
 */
public abstract class MessageEncrypt {

    /**
     * 算法实例存储容器
     */
    private static Map<String, MessageEncrypt> algorithm = new HashMap<>();

    /**
     * 算法默认id
     */
    protected static final int aid = 1;

    static {
        MessageEncrypt.put("MD5", new MD5MessageEncrypt());
        MessageEncrypt.put("COVER", new CoverMessageEncrypt());
        MessageEncrypt.put("DES", new DESMessageEncrypt());
    }

    /**
     * 编码可变长字符串为整体的字符串
     *
     * @param input 可变长字符串
     * @return
     */
    public String encode(String... input) {
        StringBuilder sb = new StringBuilder();
        for (String str : input) {
            sb.append(str);
        }
        return encode(sb.toString());
    }

    /**
     * 单个字符串 UTF-8 编码
     *
     * @param input
     * @return
     */
    public String encode(String input) {
        if (input != null) {
            byte[] b = null;
            try {
                b = encode(input.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (b != null) {
                return new String(b);
            }
        }
        return null;
    }

    /**
     * 解码
     * @param input
     * @return
     */
    public String decode(String input) {
        if (input != null) {
            byte[] b = null;
            try {
                b = decode(input.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (b != null) {
                try {
                    return new String(b, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    return new String(b);
                }
            }
        }
        return null;
    }

    /**
     * 字节数组抽象编码
     * @param input
     * @return
     */
    public abstract byte[] encode(byte[] input);

    /**
     * 字节数组抽象解码
     * @param input
     * @return
     */
    public abstract byte[] decode(byte[] input);

    public static void put(String name, MessageEncrypt alg) {
        algorithm.put(name.toUpperCase(), alg);
    }

    public static MessageEncrypt getInstance(String name) {
        return algorithm.get(name.toUpperCase());
    }

}
